<?php
namespace app\common\service;

use app\common\helper\BaseHelper;
use app\common\helper\ExcelHelper;
use app\common\model\Tag;
use app\common\model\TagUser;
use app\common\model\Visiting;
use app\common\util\Upload;
use app\common\util\Util;
use think\Model;
use app\common\model\User;
use app\common\model\UserIntegral;
use think\Request;
use app\common\model\Students;

class StudentService extends BaseService
{

    /**
     * @param $sid
     * @param $uid
     * @return array|bool|false|\PDOStatement|string|
     * 获取学员基本信息
     */
    public function getStudentInfo($sid, $uid = 0, $studentsid = 0){

        $student_info = $this->getStudentBaseInfo($sid, $uid, $studentsid);
        if($student_info){
//            $student_info['company'] = !empty($student_info['company']) ? unserialize($student_info['company']) : array();
            $student_info['company'] = !empty($student_info['company']) ? Util::unserializeStr($student_info['company']) : array();
            //手机号码隐藏中间4位  学员访问不隐藏
            if(isset($student_info['phone']) && $student_info['phone'] && $studentsid == 0){
                $student_info['phone'] = Util::hidestr($student_info['phone'],3,4);
            }
            //身份证号码隐藏4-18位
            if(isset($student_info['cardid']) && $student_info['cardid']){
                $student_info['cardid'] = Util::hidestr($student_info['cardid'],3);
            }
            //班级
            $student_info['class_info'] = $this->getStudentClass($sid, $uid, $studentsid);

            // 没有主题就返回默认主题
            if(!$student_info['homepage_style'])
            {
                $student_info['homepage_style'] = 1;
            }

            //print_r($student_info);

            // 没得顾问就设置一下顾问
            if(!$student_info['counselor_id'])
            {
                //$counselor_id =
                $user = new UserService();
                $user->getUserBaseInfo($sid,$student_info['uid']);
                //$user_info = $user->getUserByID($student_info['uid']);
                $user_info = $user->getUserBaseInfo($sid,$student_info['uid']);
                $this->set_counselor_id($sid,$user_info,0);
            }

            //签到次数
            $sign_where = [
//                'uid' => $uid,
                'sid' => $sid,
                'sign_status' => 1,
                'ourclass_status'=>1
            ];
            if($studentsid > 0){
                $sign_where['studentsid'] = $studentsid;
            } else {
                $sign_where['uid'] = $uid;
            }

            $sign_num = db()->name('course_students')
                        ->where($sign_where)
                        ->count();
            $student_info['sign_num'] = $sign_num;


            //签到率
            $course_where = [
                'uid' => $uid,
                'sid' => $sid,
                'ourclass_status'=>1
            ];
            if($studentsid > 0){
                $course_where['studentsid'] = $studentsid;
            } else {
                $course_where['uid'] = $uid;
            }

            $course_num = db()->name('course_students')
                        ->where($course_where)
                        ->count();
            if($course_num == 0){
                $student_info['sign_num'] = 0;
                $student_info['sign_rate'] = '--';
            }else{
                $sign_rate = round($sign_num/$course_num, 2) * 100;
                $student_info['sign_rate'] = $sign_rate.'%';
            }
            return $student_info;
        } else {
            return false;
        }

    }


    /**
     * 微信端: 用户访问学员个人中心
     * @param $sid
     * @param $uid
     * @param $studentsid
     * @return array|bool|false|\PDOStatement|string
     */
    public function userAccessStudents($sid, $uid, $studentsid){
        $student_info = $this->getStudentInfo($sid, 0, $studentsid);
        if(!$student_info){
            return false;
        }

        //是否为好友或同班同学
        $student_info['is_friend'] = $this->isFriend($sid, $uid, $studentsid);
        /*$friend = db('friend')->where(['my_uid' => $uid, 'friend_studentsid' => $studentsid, 'status' => 1])->find();
        if($friend){
            $student_info['is_friend'] = 1;
        } else {
            //查询是否在申请中
            $apply = db('friend_apply')->where(['sid' => $sid, 'my_uid' => $uid, 'friend_studentsid' => $studentsid, 'check_status' => 0])->find();

            //是否为同班同学
            $my_classes = db('class_students')->field('classid')->where(['uid' => $uid, 'sid' => $sid])->select();
            $students_classes = db('class_students')->field('classid')->where(['studentsid' => $studentsid, 'sid' => $sid])->select();

            if($my_classes && $students_classes){
                foreach($my_classes as $k => $v){
                    $my_class_ids[$k] = $v['classid'];
                }

                foreach($students_classes as $key => $val){
                    $students_class_ids[$key] = $val['classid'];
                }

                //交集
                $result = array_intersect($my_class_ids, $students_class_ids);
                $student_info['is_friend'] = $result ? 1 : ($apply ? 2 : 0);
            } else {
                $student_info['is_friend'] = $apply ? 2 : 0;
            }

        }*/

        return $student_info;
    }






    private function set_counselor_id($sid,$user_info,$url_counselor_id = 0)
    {
        if (!$user_info['counselor_id'] && !$user_info['counselor_status']) {
            $uid = $user_info['uid'];
            if (!$url_counselor_id) {
                $url_counselor_id = $this->getDefaultPid($sid, $uid);
            }
            if ($url_counselor_id) {

                $data_info['counselor_id'] = $url_counselor_id;
                $data_info['parent_id'] = $url_counselor_id;
                if (!$user_info['natural_id']) {
                    $data_info['natural_id'] = $url_counselor_id;
                }

                $userService = new UserService();
                //Ticket
                $userService->editUserIntegralByUserId($data_info, $sid, $uid);
                //推送消息
                $tplServer = new WxTplMsgService();
                $tplServer->send($sid,$uid,'user');

            }
        }
    }

    private function getDefaultPid($sid, $uid, $pid = 0)
    {
        $reset_parents = db('store')->where(array('store_id' => $sid))->value('reset_parents');
        $user_info = db('user_integral')->where(array('sid' => $sid, 'userid' => $uid))->field('parent_id,counselor_status')->find();
        if ($reset_parents == 1 && $user_info['parent_id'] == 0 && $user_info['counselor_status'] == 0) {
            if ($pid == 0) {

                $recommend_dis = db('store')->where(array('store_id' => $sid))->value('recommend_dis');
                if ($recommend_dis == 4) {
                    $pid = db('user_integral')->where(array('is_administrator' => 1, 'sid' => $sid))->value('userid');
                }
            }
            if ($pid) {
                return $pid;
            }
        }
        return 0;
    }
    /**
     * @param $studentModel
     * @param $request
     * @return array|bool|false|\PDOStatement|string|
     * 修改学员基本信息
     */
    public function editStudentInfo(Students $studentModel,Request $request){
        $sid = $request->param('sid');
        $uid = $request->param('uid');

        $user = $this->getStudentBaseInfo($sid, $uid);

        if (!$user){
            return ['status' => 0, 'msg' => '不存在此用户'];
        }

        $where = [
            'sid'=>$sid,
            'uid'=>$uid
        ];
        $postParam = $request->post();
        if ($request->has('user_name')){
            $update['name'] = $postParam['user_name'];
        }
        if ($request->has('user_mobile')){
            $update['phone'] = $postParam['user_mobile'];
            $update['phone_bind_status'] = 1;
        }
        if ($request->has('cardid')){
            $update['cardid'] = $postParam['cardid'];

        }
        if ($request->has('life_motto')){
            $update['life_motto'] = $postParam['life_motto'];
            //更新签名，触发钩子，记录为学员动态
            $studentsid = db('students')->where($where)->value('id');
            $param = [
                'sid' => $sid,
                'studentsid' => $studentsid,
                'type' => 1, //更新签名
                'description' => '更新了签名：'.$postParam['life_motto'],
            ];
            \think\Hook::listen('students_dynamic', $param, '', true);
        }
        if ($request->has('business')){
            $update['business'] = $postParam['business'];
            //更新主营业务，触发钩子，记录为学员动态
            $studentsid = db('students')->where($where)->value('id');
            $param = [
                'sid' => $sid,
                'studentsid' => $studentsid,
                'type' => 2, //更新主营业务
                'description' => '更新了主营业务：'.$postParam['business'],
            ];
            \think\Hook::listen('students_dynamic', $param, '', true);
        }
        if ($request->has('own_resource')){
            $update['own_resource'] = $postParam['own_resource'];
        }
        if ($request->has('needed_resource')){
            $update['needed_resource'] = $postParam['needed_resource'];
        }
        if ($request->has('company')&&!empty($postParam['company']) ){
//            $update['company'] = serialize($postParam['company']);
            $update['company'] = Util::serializeStr($postParam['company']);
        }

        $res = $studentModel->where($where)->update($update);

        if ($res === false){
            return ['status' => 0, 'msg' => '修改失败', 'data' => ''];
        } else {
            return ['status' => 1, 'msg' => '修改成功', 'data' => ''];
        }
    }

    /**
     * @param $studentModel
     * @param $request
     * @return array|bool|false|\PDOStatement|string|
     * 上传头像、背景图
     */
    public function uploadStudentImg(Students $studentModel,Request $request){
        $sid = $request->param('sid');
        $uid = $request->param('uid');

        $user = $this->getStudentBaseInfo($sid, $uid);

        if (!$user){
            return ['status' => 0, 'msg' => '不存在此用户'];
        }

        $where = [
            'sid'=>$sid,
            'uid'=>$uid
        ];
        //上传个人头像
        if ($request->file('user_headimgurl')){

            $file = $request->file('user_headimgurl'); //个人头像
            if(empty($file)){
                return ['status' => 0, 'msg' => '请选择上传图片'];
            }
            $qiniu = Upload::uploadFile();
            if($qiniu==false){
                return ['status'=> 0, 'msg'=>'上传失败', 'data' => ''];
            }else{

                $update['headimg_url'] = Util::qiniu_url($qiniu);
                $res = $studentModel->where($where)->update($update);
                if ($res === false){
                    return ['status' => 0, 'msg' => '修改失败', 'data' => ''];
                } else {
                    $data = [
                        'status'=> 1,
                        'data'=>[
                            'img_path' => $update['headimg_url']
                        ],
                        'msg'=>'上传成功'
                    ];
                    return $data;
                }
            }

        }
        //上传背景图片
        if ($request->file('homepage_bg_img')){
            $file = $request->file('homepage_bg_img'); //上传背景图片
            if(empty($file)){
                return ['status' => 0, 'msg' => '请选择上传图片'];
            }

            $qiniu = Upload::uploadFile();
            if($qiniu==false){
                return ['status'=> 0, 'msg'=>'上传失败', 'data' => ''];
            }else{
                $update['homepage_bg_img'] = Util::qiniu_url($qiniu);
                $res = $studentModel->where($where)->update($update);
                if ($res === false){
                    return ['status' => 0, 'msg' => '修改失败', 'data' => ''];
                } else {
                    $data = [
                        'status'=> 1,
                        'data'=>[
                            'img_path' => $update['homepage_bg_img']
                        ],
                        'msg'=>'上传成功'
                    ];
                    return $data;
                }
            }
        }
        return ['status' => 0, 'msg' => '请选择上传图片'];

    }

    /**
     * 学员基本信息
     * @param $sid
     * @param $uid
     * @return array|false|\PDOStatement|string|Model
     * @throws \think\Exception
     */
    public function getStudentBaseInfo($sid, $uid = 0, $studentsid = 0){
        $field = 'u.user_id as uid,u.user_nickname,u.user_headimgurl,u.user_qrcode,ui.sid,ui.students_id,ui.parent_id as counselor_id,s.name,s.headimg_url,s.phone,s.phone_bind_status,s.cardid,
                 s.company,s.business,s.life_motto,s.own_resource,s.needed_resource,s.homepage_style,s.homepage_bg_img,s.formal_status,s.access_permission';

        if($studentsid > 0){
            //通过学员ID获取信息
            $where = [
                's.id' => $studentsid,
                's.status' => 1,
                's.is_counselor' => 0,
                's.sid' => $sid
            ];
            $student_info = db('students s')
                            ->field($field)
                            ->join('user_integral ui', 'ui.userid=s.uid', 'LEFT')
                            ->join('user u', 'u.user_id=s.uid', 'LEFT')
                            ->where($where)
                            ->find();
        } else {
            $where = [
                'u.status' => 1,
                'ui.userid' => $uid,
                'ui.counselor_status' => 0,
                'ui.sid' => $sid
            ];

            $student_info = db()->name('user_integral')
                ->alias('ui')
                ->field($field)
                ->join('students s','ui.students_id = s.id','left')
                ->join('user u','ui.userid = u.user_id','left')
                ->where($where)
                ->find();
        }

        if(!$student_info){
            return false;
        }
        //个人主页默认样式
        if($student_info['homepage_style'] <= 0){
            $init_id = db('user_students_theme')->where(['sid' => $sid])->order('default_status desc')->value('init_id');
            db('students')->where(['sid'=>$sid,'uid'=>$uid])->update(['homepage_style'=>$init_id]);
            $student_info['homepage_style'] = $init_id;
        }

        return $student_info;
    }

    /**
     * 获取 学员/客户列表
     * @param $sid
     * @param $search
     * @param $p
     * @param $pageSize
     * @return mixed
     */
    public function GetStudentList($sid, $search='', $status='', $no_parent=0, $p=1, $pageSize=10, $tag=[]){
        //获取学员/顾客基本列表信息
        $where = [
            'ui.sid' => $sid,
            'ui.counselor_status' => 0,
            'u.status' => 1
        ];
        if(!empty($search)){
            $where['s.phone|u.user_nickname|s.name'] = ['like','%'.$search.'%'];
        }
//        if(!empty($status)){
//            $where['s.formal_status'] = $status;
//        }
        if($status == 1){
            $where['s.formal_status'] = $status;
        } elseif($status == 2){
            $where['s.formal_status'] = 0;
        }

        if($no_parent == 1){
            $where['ui.parent_id'] = 0;

        }

        if(!empty($tag)){
            $tag_where = [
                'store_id' => $sid
            ];
            $uids = db('tag_user')->where($tag_where)->whereIn('tag_id',$tag)->field('uid')->find();
            if(!empty($uids)){
                $uid_where = [];
                foreach($uids as $v){
                    $uid_where[] = $v['uid'];
                }
                $where['ui.userid'] = ['in',$uid_where];
            }
        }
        $list_count = db()->name('user_integral')
                        ->alias('ui')
                        ->join('students s','ui.students_id = s.id')
                        ->join('user u','ui.userid = u.user_id')
                        ->where($where)
                        ->count();
        $field = 'u.user_id as uid,u.user_nickname,u.user_headimgurl,ui.sid,ui.addtime,ui.parent_id,ui.counselor_status,ui.students_id,s.name,s.phone,s.company,s.formal_status,s.birthday,s.cardid';
        $list = db()->name('user_integral')
            ->alias('ui')
            ->field($field)
            ->join('students s','ui.students_id = s.id')
            ->join('user u','ui.userid = u.user_id')
            ->where($where)
            ->limit(($p-1) * $pageSize , $pageSize)
            ->select();
        if($list){
            $userServer = new UserService();
            $visitingServer = new VisitingService();
            $visitingModel = new Visiting();
            $tagServer = new TagService();
            foreach($list as $k => $v){
                //获取某个用户被拜访的次数
                $list[$k]['visiting_count'] = $visitingServer->getCustomerVisitingCount($visitingModel,$sid, $v['uid']);

                if($v['counselor_status'] == 0 && $v['parent_id'] > 0){
                    //获取上级（顾问）昵称
                    $list[$k]['counselor_name'] = $userServer->getUserNicknameByUID($v['parent_id']);
                } else {
                    $list[$k]['counselor_name'] = '';
                }
                //公司
//                $list[$k]['company'] = unserialize($v['company']);
//                $temp = preg_replace_callback('#s:(\d+):"(.*?)";#s',function($match){return 's:'.strlen($match[2]).':"'.$match[2].'";';}, $v['company']);
//                $list[$k]['company'] = unserialize($temp);
                $list[$k]['company'] = Util::unserializeStr($v['company']);

                $list[$k]['phone'] = Util::hidestr($v['phone'],3,4);

                //标签
                $tag= $tagServer->getUserTagList($sid, $v['uid'], 1, $v['students_id']);
                if(empty($tag)){
                    $list[$k]['system_tag']=[];
                    $list[$k]['custom_tag']=[];
                }else{
                    foreach($tag as $v){
                        if($v['type'] > 0){
                            $list[$k]['custom_tag'][] = [
                                'tag_id' => $v['tag_id'],
                                'tag_name' => $v['tag_name']
                            ];
                        }else{
                            $list[$k]['system_tag'][] = [
                                'tag_id' => $v['tag_id'],
                                'tag_name' => $v['tag_name']
                            ];
                        }
                    }
                }
            }
        }
        return ['content' => $list,'page' =>['count' =>$list_count]];
    }

    /**
     * 修改客户出单状态或者学员学生身份
     * @param $sid
     * @param $uid
     * @param $status
     * @return array
     * @throws \think\Exception
     */
    public function EditStudentFormal($sid,$uid,$status){
        $where = [
            'sid' => $sid,
            'uid' => $uid
        ];
        $res = db('students')->where($where)->update(['formal_status'=>$status,'sign_addtime' => time()]);
       if($res === false){
           return ['status' => 0];
       }else{
           return ['status' => 1];
       }
    }

    /**
     * 获取客户/学员详情
     * @param $sid
     * @param $uid
     * @return array
     */
    public function GetStudentDetail($sid,$uid){
        $student_info = $this->getStudentBaseInfo($sid,$uid);
        if(!isset($student_info['uid'])){
            return ['status' => 0];
        }
        //顾问名称
        if($student_info['counselor_id'] > 0){
            $userServer = new UserService();
            $student_info['counselor_name'] = $userServer->getUserNicknameByUID($student_info['counselor_id']);
        }else{
            $student_info['counselor_name'] = '';
        }
        //公司职位地址
//        $company = unserialize($student_info['company']);
        $company = Util::unserializeStr($student_info['company']);
        $student_info['cname'] = $company[0]['cname'];
        $student_info['position'] = $company[0]['position'];
        $student_info['address'] = $company[0]['address'];
        //客户访问文章次数，即：轨迹数量
        $trackService = new TrackService();
        $student_info['reading_count'] = $trackService->getTrackCountByOne($sid, $uid);

        //获取某个用户被拜访的次数
        $visitingModel = new Visiting();
        $visitingServer = new VisitingService();
        $student_info['visiting_count'] = $visitingServer->getCustomerVisitingCount($visitingModel,$sid, $uid);
        $student_info['visiting_new'] = $visitingServer->getCustomerVisitingNew($visitingModel,$sid,$uid);
        //班级
        $student_info['class_info'] =$this->getStudentClass($sid,$uid);
        return ['status'=>1,'data'=>['content' => $student_info]];
    }

    /**
     * 获得学员的班级
     * @param $sid
     * @param $uid
     * @return false|\PDOStatement|string|\think\Collection
     */
    public function getStudentClass($sid, $uid, $studentsid = 0, $type = 1){
        //班级
        $class_where = ['c.sid' => $sid];
        if($studentsid > 0){
            //通过学员ID获取信息
            $class_where['cs.studentsid'] = $studentsid;
        } else {
            $class_where['cs.uid'] = $uid;
        }

        $class_info = db()->name('class_students')
            ->alias('cs')
            ->join('classes c','cs.classid = c.classid', 'LEFT')
            ->field('c.name')
            ->where($class_where)
            ->select();

        $class_str = [];
        if(!empty($class_info)){
            foreach($class_info as $v){
                $class_str[] = $v['name'];
            }
            $class_info = implode('/',$class_str);
        }else{
            $class_info = '暂无';
        }

        //type = 1，返回字符串; 2返回数组
        if($type == 2){
            return $class_str;
        } else {
            return $class_info;
        }
    }

    public function getStudentClassByStudentID($sid,$studentid){
        //班级
        $class_where = [
            'cs.studentsid' => $studentid,
            'c.sid' => $sid
        ];
        $class_info = db()->name('class_students')
            ->alias('cs')
            ->join('classes c','cs.classid = c.classid', 'LEFT')
            ->field('c.name')
            ->where($class_where)
            ->select();
        if(!empty($class_info)){
            $class_str = array();
            foreach($class_info as $v){
                $class_str[] = $v['name'];
            }
            $class_info = implode('/',$class_str);
        }else{
            $class_info = '暂无';
        }
        return $class_info;
    }
    /**
     * 下载学员
     * @param $sid
     * @param $start_time
     * @param $end_time
     * @return array
     */
    public function DownStudentList($sid,$start_time,$end_time){
        $starttime = strtotime($start_time);
        $endtime = strtotime($end_time)+24*60*60-1;
        if($starttime >= $endtime){
            return ['status' => 0,'msg' => '请正确选择时间！'];
        }
        $where = [
            's.sid' => $sid,
            'ui.counselor_status' => 0,
            's.uid' =>['>',0]
        ];
        $field = 's.name,s.phone,s.business,s.company,s.uid';
        $list = db('user_integral')
                ->alias('ui')
                ->join('students s','s.id = ui.students_id')
                ->where($where)
                ->whereBetween('ui.addtime',[$starttime,$endtime])
                ->field($field)
                ->select();
        if(empty($list)){
            return ['status' => 0,'msg' => '未查询到客户'];
        }
        //头部设置

        $down_array[1] = [
            'A1' => '姓名',
            'B1' => '联系方式',
            'C1' => '公司',
            'D1' => '主营业务',
        ];

        //内容设置
        foreach($list as $k => $v){
            $key = $k+2;
            if(!empty($v['company'])){
//                $company = unserialize($v['company']);
                $company = Util::unserializeStr($v['company']);;
                if(!empty($company) && is_array($company)){
                    $company_array = [];
                    foreach($company as $val){
                        $company_array[]=$val['cname'].'/'.$val['position'].'/'.$val['address'];
                    }
                    $company_string = implode(',',$company_array);
                }else{
                    $company_string = '未完善';
                }
            }else{
                $company_string = '未完善';
            }
            $down_array[$key] = [
                'A'.$key => $v['name'],
                'B'.$key => $v['phone'],
                'C'.$key => $company_string,
                'D'.$key => $v['business'],

            ];
        }

        $filename = '学员资料'.$start_time.'---'.$end_time.'.xlsx';
        ExcelHelper::down($filename,$down_array,'studentList');
        return ['status' =>1 ];

    }

    /**
     * 获取顾问旗下的客户数量
     * @param $sid
     * @param $uid
     * @param $type 1-签单客户，0为未签单客户
     * @return int|string
     */
    public function getCustomerCount($sid,$uid,$type=1){
        $where = [
            'ui.sid' => $sid,
            'ui.parent_id' => $uid,
            'ui.userid' => ['<>', $uid],
            'ui.counselor_status' => 0,
            'ui.students_id' => ['>',0],
            's.formal_status' => $type
        ];
        $count = db('user_integral')
            ->alias('ui')
            ->join('students s','s.id = ui.students_id')
            ->where($where)
            ->count();

        // 1-签单客户
        if($type)
        {
            //这里要计算出没有激活的学员
//            $count = db('students')->where(['sid' => $sid, 'counselor_id' => $uid, 'formal_status' => 1])->count();
            $count = db()->name('students')
                ->alias('s')
                ->join('user_integral ui','ui.students_id = s.id','left')
                ->join('user u','ui.userid = u.user_id','left')
                ->where(['s.sid' => $sid, 's.counselor_id' => $uid, 's.formal_status' => 1])
                ->count();
        }

        return $count;
    }

    /**
     * 获取某个顾问旗下粉丝、签单客户、未签单客户列表
     * @param $sid
     * @param $uid
     * @param int $status 0-未签单客户，1-签单客户，2-粉丝，3-所有客户（包括签单和未签单客户）
     * @param int $p
     * @param int $pageSize
     * @return false|\PDOStatement|string|\think\Collection
     */
    public function GetCstudentList($sid,$uid,$status = 1,$p = 1, $pageSize = 10){
        /*if($status == 2){
            //获取粉丝基本列表信息
            $where = [
                'ui.sid' => $sid,
                'ui.parent_id' => $uid,
                'ui.counselor_status' => 0,
                'ui.students_id' => 0,
                'u.status' => 1
            ];

        }elseif($status == 3){
            //获取学员/顾客基本列表信息
            $where = [
                'ui.sid' => $sid,
                'ui.parent_id' => $uid,
                'ui.counselor_status' => 0,
                'ui.students_id' => ['>',0],
                'u.status' => 1
            ];
        }else{
            //获取学员/顾客基本列表信息
            $where = [
                'ui.sid' => $sid,
                'ui.parent_id' => $uid,
                'ui.counselor_status' => 0,
                'ui.students_id' => ['>',0],
                'u.status' => 1,
                's.formal_status' => $status
            ];
        }

        $list_count = db()->name('user_integral')
                        ->alias('ui')
                        ->join('students s','ui.students_id = s.id','left')
                        ->join('user u','ui.userid = u.user_id','left')
                        ->where($where)
                        ->count();
        $field = 'u.user_id as uid,u.user_nickname,u.user_headimgurl,ui.addtime,ui.sid,ui.addtime,ui.parent_id,ui.counselor_status,ui.students_id,s.name,s.phone,s.company,s.formal_status';
        $list = db()->name('user_integral')
            ->alias('ui')
            ->field($field)
            ->join('students s','ui.students_id = s.id','left')
            ->join('user u','ui.userid = u.user_id','left')
            ->where($where)
            ->limit(($p-1) * $pageSize , $pageSize)
            ->select();*/


        // ----------------粉丝查询保持不变，客户查询改为由students表为主表联表查询，目的是为了查询出通过Excel表导入的老客户（uid=0）----------------
        // By:Tangxiao
        if($status == 2){
            //获取粉丝基本列表信息
            $where = [
                'ui.sid' => $sid,
                'ui.parent_id' => $uid,
                'ui.counselor_status' => 0,
                'ui.students_id' => 0,
                'ui.userid' => ['<>', $uid],
                'u.status' => 1
            ];
            $list_count = db()->name('user_integral')
                ->alias('ui')
                ->join('students s','ui.students_id = s.id','left')
                ->join('user u','ui.userid = u.user_id','left')
                ->where($where)
                ->count();

            $field = 'u.user_id as uid,u.user_nickname,u.user_headimgurl,ui.addtime,ui.sid,ui.addtime,ui.parent_id,ui.counselor_status,ui.students_id,s.name,s.phone,s.company,s.formal_status';
            $list = db()->name('user_integral')
                ->alias('ui')
                ->field($field)
                ->join('students s','ui.students_id = s.id','left')
                ->join('user u','ui.userid = u.user_id','left')
                ->where($where)
                ->limit(($p-1) * $pageSize , $pageSize)
                ->select();
        } else {
            //获取学员/顾客基本列表信息
            $where = [
                's.sid' => $sid,
                's.counselor_id|ui.parent_id|ui.counselor_id' => $uid,
                's.uid' => ['<>', $uid]
            ];
            if($status != 3){
                // 0-未签单客户，1-签单客户
                $where['s.formal_status'] = $status;
            } else {
                //排除先成为学员后成为顾问的情况，即学员表中有数据，但此时user_integral表中又是顾问的状态
                $where['s.is_counselor'] = 0;

            }
            $list_count = db()->name('students')
                ->alias('s')
                ->join('user_integral ui','ui.students_id = s.id','left')
                ->join('user u','ui.userid = u.user_id','left')
                ->where($where)
                ->count();
            $field = 'u.user_id as uid,u.user_nickname,u.user_headimgurl,ui.addtime,ui.sid,ui.addtime,ui.parent_id,ui.counselor_status,s.id as students_id,s.name,s.phone,s.company,s.formal_status';
            $list = db()->name('students')
                ->alias('s')
                ->field($field)
                ->join('user_integral ui','ui.students_id = s.id','left')
                ->join('user u','ui.userid = u.user_id','left')
                ->where($where)
                ->limit(($p-1) * $pageSize , $pageSize)
                ->select();
        }

        if(!empty($list)){
            $trackServer = new TrackService();
            foreach($list as $k => $v){
                $list[$k]['addtime'] = $v['addtime'] ? date('Y-m-d H:i:s',$v['addtime']) : 0;
                if($v['uid']){
                    $info = $trackServer->getOneRecentTrackByOnlyCID($sid,$v['uid']);
                    $list[$k]['newtrack'] = $info['msg'];
                } else {
                    $list[$k]['newtrack'] = '';
                }
                if(!empty($v['company'])){
//                    $company = unserialize($v['company']);
                    $company = Util::unserializeStr($v['company']);;
                    $list[$k]['cname'] = $company[0]['cname']? $company[0]['cname']:'暂未填写';
                    $list[$k]['position'] = $company[0]['position']? $company[0]['position']:'暂未填写';
                    $list[$k]['address'] = $company[0]['address']? $company[0]['address']:'暂未填写';
                }else{
                    $list[$k]['cname'] ='暂未填写';
                    $list[$k]['position'] ='暂未填写';
                    $list[$k]['address'] ='暂未填写';
                }

            }
        }
        return ['content' => $list,'page' =>['count' =>$list_count]];
    }

    /**
     * 获取顾问变更记录
     * @param $sid
     * @param $uid
     * @param int $p
     * @param int $pageSize
     * @return false|\PDOStatement|string|\think\Collection
     */
    public function GetChangeLogList($sid,$uid,$p=1,$pageSize=10){
        $where = [
            'sid' => $sid,
            'uid' => $uid,
        ];
        $list_count = db('change_counselor_log')->where($where)->count();
        $list = db('change_counselor_log')
                ->where($where)
                ->order('addtime asc')
                ->limit(($p-1) * $pageSize , $pageSize)
                ->select();

        if(!empty($list)){
            foreach($list as $k=> $v){
                $list[$k]['addtime'] = date('Y-m-d H:i:s',$v['addtime']);
                $pre = db('user_integral')->alias('ui')
                       ->join('students s','s.uid = ui.userid and s.sid = ui.sid','left')
                       ->join('user u','u.user_id = ui.userid','left')
                       ->where(['ui.sid' => $sid,'ui.userid' => $v['pre_counselor_id']])
                       ->field('u.user_nickname,s.name')
                       ->find();
                $list[$k]['pre_counselor_name'] = $pre['name'] ? $pre['name'].'(真实姓名)' :$pre['user_nickname'].'(微信昵称)';

                $pre = db('user_integral')->alias('ui')
                    ->join('students s','s.uid = ui.userid and s.sid = ui.sid','left')
                    ->join('user u','u.user_id = ui.userid','left')
                    ->where(['ui.sid' => $sid,'ui.userid' => $v['cur_counselor_id']])
                    ->field('u.user_nickname,s.name')
                    ->find();
                $list[$k]['cur_counselor_name'] = $pre['name'] ? $pre['name'].'(真实姓名)' :$pre['user_nickname'].'(微信昵称)';
            }
        }
        return ['content' => $list,'page' =>['count' =>$list_count]];
    }

    /**
     * 获取本班学员
     * @param $sid
     * @param $classid
     * @param int $p
     * @param int $pageSize
     * @return false|\PDOStatement|string|\think\Collection
     */
    public function GetOwnClassStudentList($sid,$classid,$p = 1,$pageSize = 10){

        $where = [
            's.sid' => $sid,
            //'s.classid' => $classid
            // 修改判断为班级学员表里面的班级
            // 一个学员可以对应N个班级
            // 2017-08-07 LJiao
            'cs.classid' => $classid

        ];
//        $where = [
//            'cs.sid' => $sid,
//            'cs.classid' => $classid
//        ];
        $field = 'cs.*,s.*,u.user_headimgurl,u.user_nickname';
        $list_count = db('students s')
                        //->join('user_integral ui','ui.userid = s.uid','left')
                        //->join('class_students cs','s.uid = cs.uid','left')
                        ->join('class_students cs','s.id = cs.studentsid')
                        ->join('user u','u.user_id = s.uid','left')
                        ->where($where)
                        ->count();
        $list = db('students s')
            //->join('user_integral ui','ui.userid = s.uid','left')
            //->join('class_students cs','s.uid = cs.uid','left')
            ->join('class_students cs','s.id = cs.studentsid')
            ->join('user u','u.user_id = s.uid','left')
                ->where($where)
                ->field($field)
                ->order('s.uid DESC,s.id DESC')
                ->limit(($p-1)*$pageSize,$pageSize)
                ->select();
        /*$list_count = db('class_students')->alias('cs')
                        ->join('user_integral ui','ui.userid = cs.uid','left')
                        ->join('students s','s.uid = cs.uid','left')
                        ->join('user u','u.user_id = cs.uid','left')
                        ->where($where)
                        ->count();
        $list = db('class_students')->alias('cs')
                ->join('user_integral ui','ui.userid = cs.uid','left')
                ->join('students s','s.uid = cs.uid','left')
                ->join('user u','u.user_id = cs.uid','left')
                ->where($where)
                ->field($field)
                ->limit(($p-1)*$pageSize,$pageSize)
                ->select();*/
        if(!empty($list)){
            $tagServer = new TagService();
            foreach($list as $k => $v){
                if($v['company']){
//                    $list[$k]['company'] = unserialize($v['company']);
//                    $temp = preg_replace_callback('#s:(\d+):"(.*?)";#s',function($match){return 's:'.strlen($match[2]).':"'.$match[2].'";';}, $v['company']);
//                    $list[$k]['company'] = unserialize($temp);
                    $list[$k]['company'] = Util::unserializeStr($v['company']);
                }
                if($v['uid'] > 0){
                    //兴趣爱好
                    $list[$k]['tag'] = $tagServer->getUserTagList($sid,$v['uid'],2);
                    //班级
                    //$list[$k]['class_string'] = $this->getStudentClass($sid,$v['uid']);
                    $list[$k]['class_string'] = $this->getStudentClassByStudentID($sid,$v['studentsid']);
                }

            }
        }
        return ['content' => $list,'page' => ['count' => $list_count]];
    }

    /**
     * 获取非本班学员
     * @param $sid
     * @param $classid
     * @param string $search
     * @param int $p
     * @param int $pageSize
     * @return false|\PDOStatement|string|\think\Collection
     */
    public function GetNotOwnClassStudentList($sid,$classid,$search = '',$p = 1,$pageSize = 10){
        $class_where = [
            'sid' => $sid,
            'classid' => $classid
        ];
        $ids = db('class_students')->where($class_where)->field('uid')->select();
        $where = [
            'ui.sid' => $sid,
            's.formal_status' => 1
        ];
        if(!empty($ids)){
            foreach($ids as $v){
                $ids_array[] = $v['uid'];
            }
            $where['ui.userid'] = ['not in',$ids_array];
        }
        if(!empty($search)){
            $where['u.user_nickname|s.name|s.phone'] = ['like','%'.$search.'%'];
        }
        $field = 's.*,u.user_headimgurl,u.user_nickname';
        $list_count = db('user_integral')->alias('ui')
                        ->join('user u','u.user_id = ui.userid','left')
                        ->join('students s','s.uid = ui.userid and s.sid = ui.sid','left')
                        ->where($where)
                        ->count();
        $list = db('user_integral')->alias('ui')
                ->join('user u','u.user_id = ui.userid','left')
                ->join('students s','s.uid = ui.userid and s.sid = ui.sid','left')
                ->where($where)
                ->limit(($p-1)*$pageSize,$pageSize)
                ->field($field)
                ->select();
        if(!empty($list)){
            foreach($list as $k => $v){
                if($v['company']){
//                    $list[$k]['company'] = unserialize($v['company']);
//                    $temp = preg_replace_callback('#s:(\d+):"(.*?)";#s',function($match){return 's:'.strlen($match[2]).':"'.$match[2].'";';}, $v['company']);
//                    $list[$k]['company'] = unserialize($temp);
                    $list[$k]['company'] = Util::unserializeStr($v['company']);
                }
            }
        }
        return ['content' => $list,'page' => ['count' => $list_count]];
    }


    /**
     * 获取学员相册列表
     * @param $sid
     * @param $p
     * @param $pageSize
     * @return mixed
     */
    public function getStudentsAlbumList($sid, $p, $pageSize){
        $where = [
            'sid' => $sid,
            'status' => 1
        ];
        $count = db('user_students_img')->where($where)->count();

        $list = db('user_students_img us')
                ->field('us.id,us.img_url,FROM_UNIXTIME(us.addtime, \'%Y-%m-%d\') as addtime,u.user_nickname')
                ->join('user u', 'us.uid = u.user_id', 'LEFT')
                ->where(['us.sid' => $sid, 'us.status' => 1])
                ->limit(($p - 1)*$pageSize, $pageSize)
                ->select();

        $data['page']['count'] = $count;
        $data['content'] = $list;

        return $data;
    }


    /**
     * （批量）删除学员相册图片
     * @param $sid
     * @param $img_id
     * @param $batch
     * @return int
     */
    public function deleteStudentsAlbum($sid, $img_id, $batch = 0){
        $where = [
            'sid' => $sid,
            'id' => $batch == 0 ? $img_id : ['in', $img_id]
        ];
        return db('user_students_img')->where($where)->setField('status', -1);
    }

    public function completeInformation($sid,$uid,$param){
        $where = [
            'sid' => $sid,
            'uid' => $uid
        ];
        $company[0] = [
            'cname' => $param['cname'],
            'position' => $param['position'],
            'address' =>''
        ];
        $update_data = [
            'name' => $param['real_name'],
//            'company' => serialize($company)
            'company' => Util::serializeStr($company)
        ];
        $res = db('students')->where($where)->update($update_data);
        if($res === false){
            return ['status' => 0];
        }else{
            return ['status' => 1];
        }
    }


    /**
     *
     * 微信端 根据班级ID获取学员列表
     * @param $sid
     * @param $classid
     * @param $p
     * @param $pageSize
     */
    public function getStudentsListByClassid($sid, $classid, $p, $pageSize){
        $field = 'u.user_nickname,u.user_headimgurl,s.id as studentsid,s.uid,s.name,s.company,ccl.name as class_committee_title,ccl.status';
        $where = [
            'cs.sid' => $sid,
            'cs.classid' => $classid,
        ];
        //排序：班委排在最前，sorting值越小代表等级越高，但又由于联表查询，会存在sorting值为空的情况，此时会造成没有职称的学员排在最前面，故用ccl.status提前排序
        $order = 'ccl.status DESC,ccl.sorting ASC,cs.uid DESC';
        $list = db('class_students cs')
                ->field($field)
                ->join('students s', 'cs.studentsid = s.id')
                ->join('class_committee_level ccl', 'cs.class_committee_level_id = ccl.id', 'LEFT')
                ->join('user u', 'u.user_id=cs.uid', 'LEFT')
                ->where($where)
                ->order($order)
                ->limit(($p - 1)*$pageSize, $pageSize)
                ->select();
        if($list){
            foreach ($list as $k => $v) {
                if($v['company']){
                    $list[$k]['company'] = Util::unserializeStr($v['company']);
                }
                unset($list[$k]['status']);
            }
        }

        return $list;
    }


    /**
     * 微信端: 根据搜索条件搜索学员
     * @param $sid
     * @param $search
     * @param $p
     * @param $pageSize
     * @return false|\PDOStatement|string|\think\Collection
     */
    public function searchStudents($sid, $search, $p, $pageSize){
        $result = BaseHelper::searchElastic($sid,'students', $search);
        $ids = explode(',',$result);
        $where = [
            's.sid' => $sid,
            's.id' => ['in', $ids],
            's.status' => 1,
            's.is_counselor' => 0
        ];
        $field = 's.id as studentsid,s.uid,s.name,s.company,u.user_headimgurl';
        $students = db('students s')
                    ->field($field)
                    ->join('user u', 'u.user_id=s.uid', 'LEFT')
                    ->where($where)
                    ->order('uid DESC')
                    ->limit(($p - 1) * $pageSize, $pageSize)
                    ->select();

        if($students){
            foreach($students as $k => $v){
                $students[$k]['company'] = Util::unserializeStr($v['company']);
            }
        }
        return $students;
    }


    /**
     * 微信端: 设置好友访问权限
     * @param $sid
     * @param $uid
     * @param $access_permission
     * @return int
     */
    public function setAccessPermission($sid, $uid, $access_permission){
        return db('students')->where(['sid' => $sid, 'uid' => $uid])->setField('access_permission', $access_permission);
    }


    /**
     * 微信端: 获取学员公司详情
     * @param $sid
     * @param $uid
     * @return array|mixed
     */
    public function getCompanyDetail($sid, $studentsid = 0){
        $info = db('students')->field('company')->where(['id' => $studentsid, 'sid' => $sid, 'status' => 1])->find();
        if(!$info){
            return ['status' => 0, 'msg' => '用户不存在'];
        }
        $data = [];
        if($info['company']){
           $data = Util::unserializeStr($info['company']);
        }
        return $data;
    }


    /**
     * 微信端: 编辑公司信息（简介和图片）
     * @param $sid
     * @param $uid
     * @param $company
     * @return int
     */
    public function editCompany($sid, $uid, $company)
    {
        $data = Util::serializeStr($company);
        return db('students')->where(['sid' => $sid, 'uid' => $uid])->setField('company', $data);
    }

    /**
     * 判断是否为好友
     * @param $sid
     * @param $uid 当前用户ID
     * @param $studentsid 访问的学员ID
     * @return bool
     */
    public function isFriend($sid, $uid, $studentsid){
        //是否为好友或同班同学
        $friend = db('friend')->where(['my_uid' => $uid, 'friend_studentsid' => $studentsid, 'status' => 1])->find();
        if($friend){
            $is_friend = 1;
        } else {
            //查询是否在申请中
            $apply = db('friend_apply')->where(['sid' => $sid, 'my_uid' => $uid, 'friend_studentsid' => $studentsid, 'check_status' => 0])->find();

            //是否为同班同学
            $my_classes = db('class_students')->field('classid')->where(['uid' => $uid, 'sid' => $sid])->select();
            $students_classes = db('class_students')->field('classid')->where(['studentsid' => $studentsid, 'sid' => $sid])->select();

            if($my_classes && $students_classes){
                foreach($my_classes as $k => $v){
                    $my_class_ids[$k] = $v['classid'];
                }

                foreach($students_classes as $key => $val){
                    $students_class_ids[$key] = $val['classid'];
                }

                //交集
                $result = array_intersect($my_class_ids, $students_class_ids);
                $is_friend = $result ? 1 : ($apply ? 2 : 0);
            } else {
                $is_friend = $apply ? 2 : 0;
            }
        }
        return $is_friend;

      /*  //是否为好友
        $is_friend = db('friend')->where(['my_uid' => $uid, 'friend_studentsid' => $studentsid, 'status' => 1])->find();
        if(!$is_friend){
            //是否为同班同学
            $my_classes = db('class_students')->field('classid')->where(['uid' => $uid, 'sid' => $sid])->select();
            $students_classes = db('class_students')->field('classid')->where(['studentsid' => $studentsid, 'sid' => $sid])->select();
            if($my_classes && $students_classes){
                foreach($my_classes as $k => $v){
                    $my_class_ids[$k] = $v['classid'];
                }

                foreach($students_classes as $key => $val){
                    $students_class_ids[$key] = $val['classid'];
                }

                //交集
                $result = array_intersect($my_class_ids, $students_class_ids);
                return $result ? true : false;
            } else {
                return false;
            }
        } else {
            return true;
        }*/
    }

    public function getStudentInfoNew($sid, $uid, $studentsid = 0){
        $student_info = $this->getStudentBaseInfo($sid, $uid, $studentsid);
        if($student_info){
            //是否为自身
            $student_info['is_self'] = $student_info['uid'] == $uid ? 1 : 0;
            //是否为好友
            $student_info['is_friend'] = $this->isFriend($sid, $uid, $studentsid);


//            $student_info['company'] = !empty($student_info['company']) ? unserialize($student_info['company']) : array();
            $student_info['company'] = !empty($student_info['company']) ? Util::unserializeStr($student_info['company']) : array();
            //手机号码隐藏中间4位  学员访问不隐藏
            if(isset($student_info['phone']) && $student_info['phone'] && $studentsid == 0){
                $student_info['phone'] = Util::hidestr($student_info['phone'],3,4);
            }
            //身份证号码隐藏4-18位
            if(isset($student_info['cardid']) && $student_info['cardid']){
                $student_info['cardid'] = Util::hidestr($student_info['cardid'],3);
            }
            //班级
            $student_info['class_info'] = $this->getStudentClass($sid, $uid, $studentsid, 2);

            // 没得顾问就设置一下顾问
            if(!$student_info['counselor_id'])
            {
                //$counselor_id =
                $user = new UserService();
                $user->getUserBaseInfo($sid,$student_info['uid']);
                //$user_info = $user->getUserByID($student_info['uid']);
                $user_info = $user->getUserBaseInfo($sid,$student_info['uid']);
                $this->set_counselor_id($sid,$user_info,0);
            }

            $student_info['visitor_status'] = db('students')->where(['uid' => $uid, 'sid' => $sid])->value('formal_status');
            unset($student_info['counselor_id']);
            unset($student_info['homepage_style']);
            unset($student_info['homepage_bg_img']);
            return $student_info;
        } else {
            return false;
        }
    }


    public function getIntentionStudentList($sid, $active_status, $search, $p, $pageSize)
    {
        if($active_status == 1){
            $list = $this->getActiveIntentionStudentList($sid, $search, $p, $pageSize);
        } else {
            $list = $this->getInactiveIntentionStudentList($sid, $search, $p, $pageSize);
        }
        return $list;
    }


    /**
     * 获取激活的意向学员
     * @param $sid
     * @param $search
     * @param $p
     * @param $pageSize
     * @return array
     */
    public function getActiveIntentionStudentList($sid, $search, $p, $pageSize)
    {
        $where = [
            'ui.sid' => $sid,
            'ui.counselor_status' => 0,
            's.formal_status' => 0,
            'u.user_nickname|s.name|s.phone' => ['like', "%$search%"]
        ];
        $count = db('user_integral ui')
                ->join('user u', 'u.user_id=ui.userid')
                ->join('students s', 's.uid=ui.userid')
                ->where($where)
                ->count();
        $filed = 'u.user_headimgurl,u.user_nickname,s.uid,s.id,s.name,s.phone,s.company';
        $list = db('user_integral ui')
                ->join('user u', 'u.user_id=ui.userid')
                ->join('students s', 's.uid=ui.userid')
                ->field($filed)
                ->where($where)
                ->limit(($p - 1) * $pageSize, $pageSize)
                ->order('s.addtime DESC')
                ->select();
        if($list){
            foreach($list as $k => $v){
                $list[$k]['company'] = Util::unserializeStr($v['company']);
            }
        }
        $data = [
            'page' => [
                'count' => $count
            ],
            'content' => $list
        ];
        return $data;
    }

    /**
     * 获取未激活的意向学员列表
     * @param $sid
     * @param $search
     * @param $p
     * @param $pageSize
     * @return array
     */
    public function getInactiveIntentionStudentList($sid, $search, $p, $pageSize)
    {
        $where = [
            'sid' => $sid,
            'uid' => 0,
            'formal_status' => 0,
            'name|phone' => ['like', "%$search%"]
        ];

        $count = db('students')->where($where)->count();
        $list = db('students')
                ->field('id,name,phone,company')
                ->where($where)
                ->limit(($p - 1) * $pageSize, $pageSize)
                ->order('addtime DESC')
                ->select();
        if($list){
            foreach($list as $k => $v){
                $list[$k]['company'] = Util::unserializeStr($v['company']);
            }
        }

        $data = [
            'page' => [
                'count' => $count
            ],
            'content' => $list
        ];
        return $data;
    }


    /**
     * 获取学员人脸签到头像
     * @param $sid
     * @param $uid
     * @return mixed
     */
    public function getStudentAvatar($sid, $uid){
        return db('students')->where(['sid' => $sid, 'uid' => $uid])->value('avatar');
    }
}






















